package com.ds.springboot.service;

import com.alibaba.fastjson.JSON;
import com.ds.springboot.entity.PayloadDTO;
import com.ds.springboot.exception.JwtSignatureVerifyException;
import com.ds.springboot.util.JwtUtil;
import com.nimbusds.jose.JOSEException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.LocalDateTime;

/**
 * @program: springboot-1-cache
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-05-26
 **/
@Service
@Slf4j
public class TokenService {
    @Value("${my.jwt.signature.algorithm.secret}")
    private String signatureAlgorithmSecret;

    @Value("${my.jwt.expiration.time}")
    private long tokenExpirationTime;
    public boolean tokenCheck(String token){
        String payloadJsonString;
        // 验证token是否被篡改
        try {
            payloadJsonString = JwtUtil.verifySignature(token, signatureAlgorithmSecret);
        } catch (JwtSignatureVerifyException e) {
            log.error("token签名验证失败， token已经被篡改！", e);
            return false;
        } catch (JOSEException | ParseException e) {
            log.error("验证token签名时，系统异常！", e);
            return false;
        }

        /// 验证 有效负载中的其他信息 (如:过期时间、权限信息 等等)
        PayloadDTO payloadDTO = JSON.parseObject(payloadJsonString, PayloadDTO.class);
        log.info("token中存放的用户信息是 -> {}", payloadDTO);
        // token生效时间
        LocalDateTime nbf = payloadDTO.getNbf();
        log.info("token的生效时间是 -> {}", nbf);
        // token有效时长
        long exp = payloadDTO.getExp();
        log.info("token的生效时长是 -> {}", exp);
        // 当前时间
        LocalDateTime nowTime = LocalDateTime.now();
        log.info("当前时间是 -> {}", nowTime);
        //判断逻辑 如果当前时间在失效时间之前，说明token有效
        boolean isAuthorized = nbf.plusSeconds(tokenExpirationTime).isAfter(nowTime);
        log.info("token -> 【{}】是否有效？ {}", token, isAuthorized);

        if (isAuthorized) {
            return true;
        }
        log.info("认证失败，当前token已经失效");
        return false;

    }
}
